package app.controllers;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.log4j.Logger;

import app.models.Consulta;
import app.models.enums.StatusConsulta;
import app.services.ConsultaService;
import app.util.DateUtils;
import br.com.caelum.vraptor.Get;
import br.com.caelum.vraptor.Resource;

@Resource
public class TaskController extends Controller {

	private ConsultaService consultaService;
	private static final Long UM_DIA = 86400000l;
	
	private static final Logger LOGGER = Logger.getLogger(TaskController.class);
	
	public TaskController (ConsultaService consultaService){
		this.consultaService = consultaService;
	}
	
	@SuppressWarnings("deprecation")
	@Get("/task/execute")
	public void atualizaStatus(){
		List<Consulta> consultaList = new ArrayList<Consulta>();
		
		try {
			consultaList = consultaService.findAllForTask();
		} catch (ParseException e1) {
			LOGGER.error(bundle.getString("invalidationConsultsTask.error"));
		}
		
		Date nowDate = new Date();
		nowDate.setTime(nowDate.getTime() + UM_DIA);
		
		for(Consulta item: consultaList){
			try {
				if(StatusConsulta.PAGA.equals(item.getStatus())){
					if(DateUtils.convertDataStrToDate(item.getData()).getDay() > nowDate.getDay()){
						item.setStatus(StatusConsulta.ATRASADA);
						consultaService.update(item);
					}
				}
				
				if(StatusConsulta.MARCADA.equals(item.getStatus())){
					if(DateUtils.convertDataStrToDate(item.getData()).getDay() > nowDate.getDay()){
						item.setStatus(StatusConsulta.PENDENTE);
						consultaService.update(item);
					}
				}
				
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}
	}
	
}
